#!/bin/bash

echo "Preparing web interface..."

if [ -n "$1" ]; then

	TMPDIR=$1

	cp -af web web_$TMPDIR

	echo "Stripping web interface..."
	
	which java >/dev/null 2>&1
	if [ $? -ne 0 ]; then
		echo "Java Runtime Environment is missing." 1>&2
		exit 1
	fi
	
	echo "Compressing JavaScript..."
	for a in $(ls web_$TMPDIR/*.js); do
		n=$(basename $a .js)
		case "$n" in
		config)
			echo "$n.js: skipping"
			;;
		*.min)
			echo "$n.js: already minified"
			;;
		*)
			echo "$n.js -> $n.min.js"
			java -jar compiler.jar --js web_$TMPDIR/$n.js --js_output_file web_$TMPDIR/$n.min.js
			rm -f web_$TMPDIR/$n.js
			for i in $(ls web_$TMPDIR/*.{asp,inc}); do
				sed -ri "s/$n.js/$n.min.js/g" $i
			done
			;;
		esac
	done

	echo "Compressing CSS..."
	for a in $(ls web_$TMPDIR/*.css); do
		n=$(basename $a)
		echo "$n"
		java -jar closure-stylesheets.jar --output-file web_$TMPDIR/$n web_$TMPDIR/$n
	done

	echo "Compressing HTML..."
	for a in $(ls web_$TMPDIR/*.{asp,inc}); do
		n=$(basename $a)
		echo "$n"
		java -jar htmlcompressor.jar --type html --remove-intertag-spaces --compress-js --js-compressor closure --preserve-server-script --output web_$TMPDIR/$n web_$TMPDIR/$n
	done

else
	echo Usage: $0 tmpdir
fi

